<template>
  <div class="login-container">
    <video
      class="video"
      src="../../assets/video/bg-video.mp4"
      muted="muted"
      autoplay="autoplay"
      loop="loop"
    ></video>

    <div class="bg2"></div>
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm"
    >
      <h1 class="title" v-text="title"></h1>
      <i
        @click="
          isErweiLogin = !isErweiLogin;
          isSmsLogin = false;
          title = isErweiLogin ? '微信扫码登录' : '千锋管理系统';
        "
        :class="[
          'iconfont',
          'jiaobiao',
          isErweiLogin ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"
      ></i>

      <!-- 常规登录 -->
      <div class="common-login" v-if="!isErweiLogin && !isSmsLogin">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
            class="username"
          ></el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
            class="password"
          ></el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item label="验证码" prop="captcha" class="captcha">
          <el-input
            v-model="loginForm.captcha"
            class="captchaIpt"
            @keydown.native.enter="submitForm('loginForm')"
            @keydown.native.right="updateCaptcha"
          ></el-input>
          <span class="captcha-svg" v-loading="captchaLoading">
            <i v-html="captchaSvg" @click="updateCaptcha"></i>
          </span>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('loginForm')"
            class="submitBtn"
            >提交</el-button
          >
        </el-form-item>

        <!-- 切换短信登录 -->
        <div class="changeToSms">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-iphone"></use>
          </svg>
          <a href="javascript:;" @click="isSmsLogin = !isSmsLogin"
            >切换短信登录</a
          >
        </div>
      </div>

      <!-- 二维码登录 -->
      <div class="erweiLogin" v-else-if="isErweiLogin && !isSmsLogin">
        <div class="img" v-loading="erweimaLoading">
          <img :src="qrDataUrl" alt="" width="200" height="200" />
          <i
            class="mask"
            :style="qrStyle"
            v-show="showQrMask"
            @click="getQrcode"
          ></i>
        </div>
        <p>
          <svg class="icon erweiLoginWeixin" aria-hidden="true">
            <use xlink:href="#icon-weixin"></use>
          </svg>
          <i v-text="erweiLoginMsg"></i>
        </p>
      </div>

      <!-- 短信验证登录 -->
      <div class="smsLogin" v-else>
        <el-form-item label="手机号">
          <el-input
            maxlength="11"
            v-model="phoneNumber"
            class="phoneIpt"
          ></el-input>
          <span
            class="sendSmsCode"
            @click="sendSmsCode"
            v-html="smsRetryMsg"
          ></span>
        </el-form-item>

        <el-form-item label="验证码">
          <el-input maxlength="5" v-model="smsCode"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="submitBtn" @click="smsSubmit"
            >提交</el-button
          >
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
//引入api中的方法
import * as api from "../../api/login";

//引入扫码成功和失败的图片
import scanCodeSuccessPic from "@/assets/img/scancode.png";
import invalidPic from "@/assets/img/invalidQr.png";

//引入socket
import socketIo from "socket.io-client";

//引入qrcode
import qr from "qrcode";

//映射vuex
import { mapMutations } from "vuex";

// 校验验证码
var validateCaptcha = (rule, value, callback) => {
  //value是输入框的内容
  //callback如果不传参，代表校验通过，如果传参，代表校验不通过
  const valueLength = value.split("").length;
  //console.log(valueLength);
  if (valueLength === 5) {
    callback();
  } else {
    callback("验证码必须是五位数");
  }
};

// 校验用户名
var validateUsername = (rule, value, callback) => {
  //value就是输入框的内容
  //callback如果不传参，代表校验通过，如果传参，表示校验不通过
  var userNamePattern = /^[a-zA-Z0-9_-]{4,16}$/;
  if (userNamePattern.test(value)) {
    callback();
  } else {
    callback("用户名格式必须是4到16位（字母，数字，下划线，减号）");
  }
  //console.log(value);
};

// 校验密码
var validatePassword = (rule, value, callback) => {
  //value就是输入框的内容
  //callback如果不传递参数，代表校验通过，如果传递参数则代表校验不通过
  const valueLength = value.split("").length;
  //console.log(valueLength);
  if (valueLength < 5) {
    callback("密码长度必须是五位以上");
  } else {
    callback();
  }
};

export default {
  mounted() {
    this.updateCaptcha();
  },
  name: "login",
  data() {
    return {
      smsDisabled: false,
      smsSecond: "",
      smsRetryMsg: "点击发送验证码",
      showQrMask: false, //是否显示二维码遮罩
      isScanCodeSuccess: false,
      qrDataUrl: "",
      qrStyle: {
        backgroundImage: `url(${invalidPic})`,
        backgroundSize: "50%",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center",
      },
      smsCode: "",
      phoneNumber: "",
      isSmsLogin: false,
      erweiLoginMsg: "请使用手机扫码登录",
      captchaLoading: false,
      erweimaLoading: false,
      captchaSvg: "",
      isErweiLogin: false,
      title: "千锋管理系统",
      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapMutations(["SET_USERINFO"]),
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        //console.log(valid);
        if (valid) {
          //本地表单校验通过
          let { username, password, captcha } = this.loginForm;
          //开始校验验证码
          api.verifyCaptcha(captcha).then(async (res) => {
            //console.log(res.data);
            let { msg, state } = res.data;
            if (state) {
              //验证码正确
              //加载登录等待动画
              const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
              });
              let res = await api.commonLogin(username, password);
              //console.log(res);
              //console.log(res.data);
              let { state: loginState, msg, token, userInfo, permission: {buttons}} = res.data;
              // console.log(token);
              // console.log(userInfo);
              if (loginState) {
                //登录成功
                //关闭登录等待加载动画
                loading.close();
                //将token,userInfo,permissionBtn存储到localStorage里面
                localStorage.setItem("yz-token", token);
                localStorage.setItem("yz-userInfo",JSON.stringify(userInfo));
                localStorage.setItem("yz-permissionBtn", JSON.stringify(buttons));
                //调用vuex的方法，设置用户信息
                this.SET_USERINFO(userInfo);
                //跳转页面
                this.$router.push("/");
                this.$message({
                  message: msg,
                  duration: 1000,
                  type: "success",
                });
              } else {
                //登录失败
                //关闭登录等待加载动画
                loading.close();
                // this.$confirm(msg,"提示", {
                //   type: "error",
                // });
              }
            } else {
              //验证码错误
              //关闭登录
              // this.$confirm(msg,"提示", {
              //     type: "error",
              //   });
              this.updateCaptcha();
            }
          });
        } else {
          //本地表单校验不通过
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    updateCaptcha() {
      //得到验证码之前打开加载动画
      this.captchaLoading = true;

      api.getCaptcha().then((res) => {
        //console.log(res);
        this.captchaSvg = res.data.img;

        //得到验证码之后关闭加载动画
        this.captchaLoading = false;
      });
    },
    getQrcode(sid) {
      //清掉之前的二维码图片
      this.qrDataUrl = "";
      //关掉遮罩
      this.showQrMask = false;
      //加载动画
      this.erweimaLoading = true;
      sid = localStorage.getItem("yz-sid") ?? sid;
      api.getQrcode(sid).then((res) => {
        //console.log(res);
        let { scanCodeUrl, state: getQrcodeState } = res.data;
        //console.log(scanCodeUrl);
        //console.log(getQrcodeState);
        if (getQrcodeState) {
          qr.toDataURL(scanCodeUrl, (err, imageBase64Url) => {
            if (err) {
              this.$messageBox.error(err);
              return;
            } else {
              this.qrDataUrl = imageBase64Url;
              //关闭加载动画
              this.erweimaLoading = false;

              //关闭遮罩
              this.showQrMask = false;

              //修改提示文字
              this.erweiLoginMsg = "请使用手机扫码登录";
            }
          });
        }
      });
    },
    //调用接口发送验证码
    async sendSmsCode() {
      if (this.smsDisabled) {
        this.$message.error("一分钟只能发送一次");
        return;
      }
      let smsGetCaptchaRes = await api.getSmsCaptcha(this.phoneNumber);
      console.log(smsGetCaptchaRes);
      let {
        data: { state: sendSmsCodeState },
      } = smsGetCaptchaRes;
      if (sendSmsCodeState) {
        this.$message.success("短信发送成功");
        this.smsDisabled = true;
        this.smsSecond = 60;
        this.smsInterval = setInterval(() => {
          this.smsSecond--;
          if (this.smsSecond === 0) {
            clearInterval(this.smsInterval);
            this.smsRetryMsg = "点击发送验证码";
            this.smsDisabled = false;
            return;
          }
          this.smsRetryMsg = `${this.smsSecond}秒后重发`;
        }, 1000);
      }
    },
    //调用接口手机登录
    async smsSubmit() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let smsLoginRes = await api.smsLogin(this.smsCode);
      console.log(smsLoginRes);
      let {
        data: {
          permission: { buttons },
          state,
          token,
          userInfo,
        },
      } = smsLoginRes;
      //将permission里面的buttons,token,userInfo存储在本地
      if (state) {
        //localStorage存储的内容必须是字符串，所以需要JSON.stringify()
        localStorage.setItem("yz-permissionBtn", JSON.stringify(buttons));
        localStorage.setItem("yz-token", token);
        localStorage.setItem("yz-userInfo",JSON.stringify(userInfo))

        //调用vuex的方法，存储用户信息
        this.SET_USERINFO(userInfo);
 
        this.$router.push("/");
        loading.close();
      }
    },
  },
  //监听isErweiLogin
  watch: {
    isSmsLogin(val) {
      if (!val) {
        if (this.smsInterval) {
          clearInterval(this.smsInterval);
        }
        this.smsDisabled = false;
        this.smsRetryMsg = "点击发送验证码";
      }
    },
    isErweiLogin(isErwei) {
      //console.log(isErwei);
      if (isErwei) {
        //切换成二维码登录之后
        //二维码加载动画
        this.erweimaLoading = true;
        //建立socketIo链接
        let io = socketIo("wss://chst.vip");
        //console.log(io);

        //监听socketIo的connectSuccess事件
        //连接成功
        io.on("connectSuccess", (data) => {
          //console.log(data);
          let sid = data.sid;
          localStorage.setItem("yz-sid", sid);
          //调用获取二维码的方法
          this.getQrcode(sid);
        });
        //扫码成功
        io.on("scancodeSuccess", (data) => {
          //显示二维码的遮罩，并且将二维码图片换为扫码成功的图片
          this.showQrMask = true;
          this.qrStyle.backgroundImage = `url(${scanCodeSuccessPic})`;
          //console.log(data);
          let { state: scancodeState, wechatCode } = data;
          if (scancodeState) {
            //扫码成功了
            api.wechatLogin(wechatCode).then((scancodeRes) => {
              //console.log(scancodeRes);
              //解构内容
              let {
                permission: { buttons },
                state,
                token,
                userInfo,
              } = scancodeRes.data;
              //将permission里面的buttons,token,userInfo存储在本地
              if (state) {
                //localStorage存储的内容必须是字符串，所以需要JSON.stringify()
                localStorage.setItem(
                  "yz-permissionBtn",
                  JSON.stringify(buttons)
                );
                localStorage.setItem("yz-token", token);
                localStorage.setItem("yz-userInfo",JSON.stringify(userInfo))
                //调用vuex的方法，设置用户信息
                this.SET_USERINFO(userInfo);
                this.$router.push("/");
                //跳转之后，关闭二维码遮罩
                this.showQrMask = false;
                //跳转之后，关闭加载动画
                this.erweimaLoading = false;
              }
            });
          }
        });
        //二维码失效
        io.on("invalidCode", (data) => {
          //console.log(data);
          this.showQrMask = true;
          this.erweiLoginMsg = "二维码失效";
        });
      }
    },
  },
};
</script>
<style lang="less" scoped>
.login-container {
  position: relative;
  .video {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
  .bg2 {
    background-image: url("../../assets/img/bg2.png");
    background-repeat: no-repeat;
    position: fixed;
    left: 0;
    top: 0;
    width: 20%;
    height: 40%;
    background-size: 100%;
    left: 20%;
    top: 40%;
    opacity: 0.5;
  }

  .login-loginForm {
    width: 400px;
    position: fixed;
    right: 10%;
    top: 25%;
    text-align: center;
    background-color: rgba(0, 0, 0, 0.3);
    .title {
      margin: 80px 0 60px 0;
      text-align: center;
      color: #fff;
    }
    .jiaobiao {
      font-size: 60px;
      color: #fff;
      position: absolute;
      right: 0px;
      top: -3px;
      cursor: pointer;
      opacity: 0.7;
    }
    /deep/ .el-form-item__label {
      color: #fff;
    }
    .el-form-item__content {
      width: 250px;
    }
    .el-form-item {
      margin-right: 50px;
    }
    /deep/ .captcha .el-form-item__content {
      display: flex;
    }
    /deep/ .el-input__inner {
      border: 0;
    }
    /deep/ .captchaIpt {
      width: 100px;
      .el-input__inner {
        vertical-align: top;
        border-radius: 5px 0 0 5px;
      }
    }
    /deep/ .captcha-svg {
      width: 150px;
      height: 40px;
      display: inline-block;
      background-color: #fff;
      text-align: center;
      border-radius: 0 5px 5px 0;
    }
    .submitBtn {
      width: 250px;
    }
    .changeToSms {
      margin-bottom: 30px;
    }
    .changeToSms a {
      color: #fff;
    }

    .erweiLogin {
      .img {
        position: relative;
        width: 200px;
        left: 25%;
        .mask {
          position: absolute;
          top: 0;
          left: -100px;
          transform: translate(50%);
          background-color: #fff;
          opacity: 0.8;
          display: block;
          width: 200px;
          height: 200px;
          cursor: pointer;
        }
      }
      p {
        color: #fff;
        .erweiLoginWeixin {
          width: 1.5em;
          vertical-align: -10px;
        }
      }
    }

    .smsLogin {
      .phoneIpt {
        width: 140px;
        /deep/ .el-input__inner {
          border-radius: 5px 0 0 5px;
          vertical-align: top;
        }
      }
      .sendSmsCode {
        width: 110px;
        display: inline-block;
        background-color: #fff;
        border-radius: 0 5px 5px 0;
        cursor: pointer;
      }
      .submitBtn {
        width: 250px;
        margin-bottom: 30px;
      }
    }
  }
}
</style>